package com.kuaifawu.lwnlawyerclient.Fragment;

import android.animation.ObjectAnimator;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.graphics.Matrix;

import com.kuaifawu.lwnlawyerclient.Activity.GrowMedalActivity;
import com.kuaifawu.lwnlawyerclient.Activity.LWNLoginActivity;
import com.kuaifawu.lwnlawyerclient.Activity.MainActivity;
import com.kuaifawu.lwnlawyerclient.Adapter.LWNAdapter_lawyerInfo;
import com.kuaifawu.lwnlawyerclient.Lib.CircularImage;
import com.kuaifawu.lwnlawyerclient.Lib.LWNJsonToData;
import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_lawyerInfo;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_user;
import com.kuaifawu.lwnlawyerclient.R;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;


import org.json.JSONObject;

public class LWNLawyerCenterFragment extends Fragment implements View.OnTouchListener, View.OnClickListener{
    @ViewInject(R.id.lc_level)
    private TextView textView_level;
    @ViewInject(R.id.lc_name)
    private TextView textView_name;
    @ViewInject(R.id.lc_sign)
    private TextView textView_sign;
    @ViewInject(R.id.lc_qbg)
    private ImageView imageView_qbg;
    @ViewInject(R.id.lc_portrait)
    private CircularImage imageView_portrait;
    @ViewInject(R.id.lc_jiangzhang)
    private ImageButton button_jiazhang;
    @ViewInject(R.id.lc_pingjia)
    private TextView textView_pingjia;
    @ViewInject(R.id.lc_jiejue)
    private TextView textView_jiejue;
    @ViewInject(R.id.lc_jifen)
    private TextView textView_jifen;
    @ViewInject(R.id.lc_down)
    private ImageButton button_down;
    @ViewInject(R.id.lc_moveback)
    private LinearLayout view_moveBack;
    @ViewInject(R.id.lc_la_xunzhang)
    private LinearLayout view_xunzhang;
    @ViewInject(R.id.listView_lawyer)
    private ListView list_lawyer;
    @ViewInject(R.id.lc_innerback)
    private ImageView lc_innerback;
    @ViewInject(R.id.rel_ayout_con)
    private RelativeLayout rel_ayout_con;
    @ViewInject(R.id.lc_bg)
    private ImageView lc_bg;
    @ViewInject(R.id.textView_sign_one)
    private TextView textView_sign_one;
    @ViewInject(R.id.textView_sign_two)
    private TextView textView_sign_two;
    @ViewInject(R.id.textView_sign_three)
    private TextView textView_sign_three;
    @ViewInject(R.id.line_labs)
    private LinearLayout line_labs;
    @ViewInject(R.id.imageView_labs_line)
    private ImageView imageView_labs_line;

    private  int windownHigth=0;
    private  int windownWid=0;
    private View blankView=null;
    private LayoutInflater mflater;
   private  Window  window;
    Matrix matrix = new Matrix();
    Bitmap bitmap;

    public LWNLawyerCenterFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_lawyercenter, container, false);
        ViewUtils.inject(this, rootView);
       //getLawyerInfoFromNetwork();

        rootView.setOnTouchListener(this);
       // isVirtuakey();
        return rootView;
    }


    private void initView(){
        button_jiazhang.setOnClickListener(this);
        LWNModel_lawyerInfo lawyer = LWNModel_lawyerInfo.getInstance();

        BitmapUtils bitmapUtils = new BitmapUtils(getActivity());
        bitmapUtils.configDefaultLoadingImage(R.drawable.qd_youtouxiang);//默认背景图片
        bitmapUtils.configDefaultLoadFailedImage(R.drawable.qd_youtouxiang);//加载失败图片
        bitmapUtils.display(imageView_portrait, lawyer.getHead_src());

        textView_name.setText(lawyer.getRealname());
        textView_level.setText("LV." + lawyer.getString_class());
        textView_sign.setText(lawyer.getSignatu());
        textView_pingjia.setText(lawyer.getEvaluation());
        textView_jiejue.setText(lawyer.getSolvecount());
        textView_jifen.setText(lawyer.getIntegral());

        int jiangzhang = Integer.parseInt(LWNModel_lawyerInfo.getInstance().getLabel());
        switch (jiangzhang){
            case 0:{
                button_jiazhang.setImageDrawable(getResources().getDrawable(R.drawable.lc_jz_no));
            }break;
            case 1:{
                button_jiazhang.setImageDrawable(getResources().getDrawable(R.drawable.lc_jz_daren_small));
            }break;
            case 2:{
                button_jiazhang.setImageDrawable(getResources().getDrawable(R.drawable.lc_jz_mingxing_small));
            }break;
        }
        if(list_lawyer!=null&&blankView!=null){
            list_lawyer.removeFooterView(blankView);
        }
        mflater = LayoutInflater.from(getActivity());
        blankView=(View)mflater.inflate(R.layout.centen_blankfoot,null);

        list_lawyer.addFooterView(blankView);
        LWNAdapter_lawyerInfo lawyerInfo = new LWNAdapter_lawyerInfo(getActivity(), R.layout.fragment_lawyercenter, null);
        list_lawyer.setAdapter(lawyerInfo);

        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        //    Display display = wManager.getDefaultDisplay();
        windownHigth = dm.heightPixels;
        windownWid = dm.widthPixels;

        button_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               // getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
                viewChange();
            }
        });
        setLab(lawyer);

       // setscrollList();
        if(!isMove){
            scaleView(imageView_portrait, 0.5f, 0.5f, 0.5f,true);
        }
    }



    public void LoadDataWithActivity(MainActivity activity_main){
        mainActivity = activity_main;

    }
private MainActivity mainActivity;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.lc_jiangzhang:
               // mainActivity.centerSkipGrow(1);
                  Intent intent=new Intent(getActivity(), GrowMedalActivity.class);
                Bundle bundle=new Bundle();
                bundle.putInt("index",1);
                intent.putExtras(bundle);
                startActivity(intent);

                break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //initView();
       getLawyerInfoFromNetwork();
        MobclickAgent.onPageStart("MainScreen");
        //MobclickAgent.onResume(getActivity());
        //getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainScreen");
        //MobclickAgent.onPause(getActivity());
    }

    //获取律师信息
    public void getLawyerInfoFromNetwork() {
        final ProgressDialog proDialog = android.app.ProgressDialog.show(getActivity(), "", getResources().getString(R.string.toast_wait));
        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        String string_url = center.getInstance().getLawyerInfo(getActivity());
        //System.out.println(string_url);
        HttpUtils http = center.getUtils();
        http.configCurrentHttpCacheExpiry(0*0);
        http.send(HttpRequest.HttpMethod.GET,
                string_url,
                new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                        proDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                            String string_code = jsonObject.getString("code");
                            String string_msg = jsonObject.getString("msg");
                            switch (Integer.parseInt(string_code)) {
                                case 10000:{
                                    JSONObject json_object = jsonObject.getJSONObject("data");
                                    LWNJsonToData.saveLawyerInfoWithJsonString(json_object);
                                    initView();
                                }break;
                                case 10001:{
                                    Toast toast = Toast.makeText(getActivity().getApplicationContext(),
                                            string_msg, Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    LinearLayout toastView = (LinearLayout) toast.getView();
                                    ImageView imageCodeProject = new ImageView(getActivity().getApplicationContext());
                                    imageCodeProject.setImageResource(R.drawable.error);
                                    toastView.addView(imageCodeProject, 0);
                                    toast.show();
                                }break;
                                case 10003: {
                                    String token = LWNModel_user.getInstance().getString_token(getActivity());
                                    if (token != null) {
                                        Toast toast = Toast.makeText(getActivity().getApplicationContext(),
                                                string_msg, Toast.LENGTH_SHORT);
                                        toast.setGravity(Gravity.CENTER, 0, 0);
                                        LinearLayout toastView = (LinearLayout) toast.getView();
                                        ImageView imageCodeProject = new ImageView(getActivity().getApplicationContext());
                                        imageCodeProject.setImageResource(R.drawable.error);
                                        toastView.addView(imageCodeProject, 0);
                                        toast.show();
                                        Intent intent = new Intent();
                                        intent.setClass(getActivity(), LWNLoginActivity.class);
                                        startActivity(intent);
                                        getActivity().finish();
                                    }
                                }
                                break;
                                default: {
                                    Toast toast = Toast.makeText(getActivity().getApplicationContext(),
                                            string_msg, Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    LinearLayout toastView = (LinearLayout) toast.getView();
                                    ImageView imageCodeProject = new ImageView(getActivity().getApplicationContext());
                                    imageCodeProject.setImageResource(R.drawable.error);
                                    toastView.addView(imageCodeProject, 0);
                                    toast.show();
                                }
                                break;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        proDialog.dismiss();
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                }
        );
    }

    //移动动画
    public void moveView(final View view_move, final float p1) {
        ObjectAnimator.ofFloat(view_move, "translationY", -p1)
                .setDuration(500).start();
    }

    //渐变
    public void shadeView(final View view_shave, Boolean apl){
        if(apl) {
            Animation animation = new AlphaAnimation(1.0f, 0.0f);
            animation.setDuration(500);
            animation.setFillAfter(true);
            view_shave.startAnimation(animation);

        }
        else{
            Animation animation = new AlphaAnimation(0.0f, 1.0f);
            animation.setDuration(500);
            animation.setFillAfter(true);
            view_shave.startAnimation(animation);
        }
    }

    //缩放
    public void scaleView(final View view_scale, float size, float position_x, float position_y,boolean ischange){
        ScaleAnimation animation = null;
        if(ischange){
        animation = new ScaleAnimation(1.0f, size, 1.0f, size,
                    Animation.RELATIVE_TO_SELF, position_x, Animation.RELATIVE_TO_SELF, position_y);
        }else{
            animation = new ScaleAnimation(0.5f, size, 0.5f, size,
                    Animation.RELATIVE_TO_SELF, position_x, Animation.RELATIVE_TO_SELF, position_y);
        }
//        ScaleAnimation animation = new ScaleAnimation(1.0f, size, 1.0f, size,
//                Animation.RELATIVE_TO_SELF, position_x, Animation.RELATIVE_TO_SELF, position_y);
        animation.setDuration(500);
        animation.setFillAfter(true);
        view_scale.startAnimation(animation);
    }
    //属性的动画
    public void propertyView(View view,boolean change) {
        //TranslationY:属性9
        //300偏移量


        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        //    Display display = wManager.getDefaultDisplay();
        int windownHigth = dm.heightPixels;
        int windownWid = dm.widthPixels;
        int xdpi = (int) dm.xdpi;
        float density=dm.density;
        int move=0;
        if (windownWid == 720) {//三星,小米适配
            move=35;
        }else{
            move=90;
        }
            if(change){
//                ObjectAnimator.ofFloat(view, "translationY", -((windownHigth / 5) * 3) - move)
//                 .setDuration(500).start();

                ObjectAnimator.ofFloat(view, "translationY", -((windownHigth / 5) * 3) - 10)
                        .setDuration(500).start();

            }else{
//                ObjectAnimator.ofFloat(view, "translationY", ((windownHigth / 5) * 3) - move)
//                        .setDuration(500).start();
                ObjectAnimator.ofFloat(view, "translationY", ((windownHigth / 5) * 3) - 10)
                        .setDuration(500).start();
            }

//        int[] location = new int[2];
//        view.getLocationOnScreen(location);
//        ObjectAnimator.ofFloat(view, "translationY", -((location[1] / 5) * 3) - 70)
//                .setDuration(500).start();


    }
     private  float oldY=0;
     private  float newY=0;
     private boolean isMove=true;
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                //getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
                oldY=event.getY();

                break;

            case MotionEvent.ACTION_UP:
                //getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
                newY=event.getY();
                if((newY-oldY)>10){

                    if(!isMove){
                        viewReduction();
                    }


                }else if((newY-oldY)<-10){
                  //  Toast.makeText(getActivity(),"向上",Toast.LENGTH_SHORT).show();
                    if(isMove){
                        viewChange();
                    }

                }

                break;
        }



        return true;
    }

    /**
     * 改变View向上滑动
     */
    private void viewChange(){
        button_jiazhang.setClickable(false);
        shadeView(textView_sign, true);
        shadeView(view_xunzhang, true);
        shadeView(button_down, true);

        int move=0;
        int backMove=0;
        switch (windownWid){
            case 1440://联想
                move=320;//130
                backMove=400;
                break;
            case 720://三星
                move=90;//130
                backMove=250;
                break;
            case 480://vivo
                move=20;
                backMove=210;
                break;
            case 1080://华为
                move=160;//130
                backMove=400;
                break;
            default:
                move=80;
                backMove=180;
                break;

        }
        backMove += 100;
//        if(windownWid==1440){
//            move=320;//130
//            backMove=400;
//        }else if(windownWid==720){
//            move=120;//130
//            backMove=250;
//        }else if (windownWid==480){
//            move=120;
//            backMove=300;
//        }else{
//            move=100;
//            backMove=180;
//        }

        moveView(textView_name, move);//名字100
        moveView(view_moveBack, backMove);//250
        moveView( lc_bg, 180);//240

        scaleView(imageView_portrait, 0.5f, 0.5f, 0.5f,true);
        scaleView(imageView_qbg, 0.5f, 0.5f, 0.5f,true);
        scaleView(textView_level, 0.5f, -0.5f, -1.0f,true);
        propertyView(list_lawyer, true);

        propertyView(line_labs, true);
        propertyView(imageView_labs_line,true);

        isMove=false;

    }

    /**
     * 向下滑动
     */
    private void viewReduction(){
        button_jiazhang.setClickable(true);
        shadeView(textView_sign, false);
        shadeView(view_xunzhang, false);
        shadeView(button_down, false);

        moveView(textView_name, 0);//名字100
        moveView(view_moveBack, 0);
        moveView( lc_bg, 0);
        propertyView(list_lawyer,false);
        propertyView(line_labs,false);
        propertyView(imageView_labs_line,false);
        scaleView(imageView_portrait, 1.0f, 0.5f, 0.5f,false);
        scaleView(imageView_qbg, 1.0f, 0.5f, 0.5f,false);
        scaleView(textView_level, 1.0f, -0.5f, -1.0f,false);
//        view_xunzhang.setVisibility(View.VISIBLE);
//        button_down.setVisibility(View.VISIBLE);
//        imageView_portrait.setVisibility(View.VISIBLE);
//        imageView_qbg.setVisibility(View.VISIBLE);
        isMove=true;


    }


    private void setLab( LWNModel_lawyerInfo lawyerInfo){
        textView_sign_two.setText(lawyerInfo.getLife() + "年经验");
        textView_sign_three.setText(lawyerInfo.getPosition());
        int kind_content = Integer.parseInt(lawyerInfo.getGoodatfield());
        switch (kind_content) {
            case 0: {
                textView_sign_one.setText("专长：婚姻家庭");
            }
            break;
            case 1: {
                textView_sign_one.setText("专长：房屋买卖");
            }
            break;
            case 2: {
                textView_sign_one.setText("专长：债务纠纷");
            }
            break;
            case 3: {
                textView_sign_one.setText("专长：劳动争议");
            }
            break;
            case 4: {
                textView_sign_one.setText("专长：交通肇事");
            }
            break;
            case 5: {
                textView_sign_one.setText("专长：刑事案件");
            }
            break;
            case 6: {
                textView_sign_one.setText("专长：其他类型");
            }
            break;
            case 11: {
                textView_sign_one.setText("专长：公司注册");
            }
            break;
            case 12: {
                textView_sign_one.setText("专长：投资融资");
            }
            break;
            case 13: {
                textView_sign_one.setText("专长：股权期权");
            }
            break;
            case 14: {
                textView_sign_one.setText("专长：合同事项");
            }
            break;
            case 15: {
                textView_sign_one.setText("专长：知识产权");
            }
            break;
            case 16: {
                textView_sign_one.setText("专长：财税事务");
            }
            break;
            case 17: {
                textView_sign_one.setText("专长：劳动人事");
            }
            break;
            case 18: {
                textView_sign_one.setText("专长：债务纠纷");
            }
            break;
            case 19: {
                textView_sign_one.setText("专长：其他问题");
            }
            break;
            default:
                break;
        }
    }


    /**
     * 设置listView的滚动动画
     */
    private float listTochheight=-1;
    private float myy=-1;
   private  float newy=-1;
    private void setscrollList(){
        list_lawyer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                 final int action=event.getAction();
               switch (action&MotionEvent.ACTION_MASK){
                   case MotionEvent.ACTION_DOWN:
                       myy=event.getY();
                       break;
                   case MotionEvent.ACTION_UP:
                       newy=event.getY();
                       listTochheight=myy-newy;
                       break;

               }

                return false;
            }
        });
        list_lawyer.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                int hei=view.getChildAt(0).getTop();
                if(scrollState==0&&listTochheight<0&&hei==0){//先向上判断listView的滑动的方向再判断是否已经滑动到顶部
                     viewReduction();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {



            }
        });
    }




}
